package com.jkoss.wine.merchant.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.merchant.entity.MerchantProduct;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.service.IMerchantProductNormService;
import com.jkoss.wine.merchant.service.IMerchantProductService;
import com.jkoss.wine.merchant.service.IMerchantProductTypeService;
import com.jkoss.wine.merchant.vo.MerchantProductVo;
import com.jkoss.wine.merchantSetting.service.IMerchantAssetService;
import com.jkoss.wine.shop.entity.Shop;
import com.jkoss.wine.shop.service.IMerchantCommonTypeService;
import com.jkoss.wine.shop.service.IMerchantProductPicsService;
import com.jkoss.wine.system.entity.Role;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**
 * 商品设置
 * 
 * @Author Ning
 * @Version 1.0, 2018-09-28
 * @See
 * @Since com.jkoss.mengal.merchant.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/merchant/merchantProduct")
public class MerchantProductController extends BaseController {

	@Autowired
	private IMerchantProductService iMerchantProductService;
	@Autowired
	private IMerchantProductTypeService iMerchantProductTypeService;

	@Autowired
	private IMerchantCommonTypeService iMerchantCommonTypeService;
	@Autowired
	private IMerchantAssetService iMerchantAssetService;
	@Autowired
	private IMerchantProductNormService iMerchantProductNormService;
	@Autowired
	private IMerchantProductPicsService iMerchantProductPicsService;

	// @RequestMapping("/list")
	// @RequiresPermissions("/merchant/merchantProduct/list")
	// public String list(String productName,Integer state,DwzPageBean dwzPageBean,
	// ModelMap map, String id, HttpServletRequest request, HttpServletResponse
	// response) {
	// dwzPageBean.getCountResultMap().put("productName", productName);
	// dwzPageBean.getCountResultMap().put("state", state);
	// Wrapper wrapper = Condition.create().ne("state", 1).like("mp.product_name",
	// productName);
	// map.put("types", iMerchantProductTypeService.selectByTypeId());
	// Page resultPage =
	// iMerchantProductService.selectVoByPage(dwzPageBean.toPage(), wrapper);
	// map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
	// return "merchant/merchantProduct/list";
	// }
	/**
	 * 列表
	 * 
	 * @param productName
	 * @param state
	 * @param dwzPageBean
	 * @param map
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list")
	@RequiresPermissions("/merchant/merchantProduct/list")
	public String list(String productName, Integer state, DwzPageBean dwzPageBean, ModelMap map, String id, HttpServletRequest request, HttpServletResponse response) {

		String string = request.getParameter("org2.productName");
		// 前端框架bean
		dwzPageBean.getCountResultMap().put("productName", string);
		dwzPageBean.getCountResultMap().put("state", state);
		// 构建排序条件 构建排序条件 是否删除：0-未删除、1-已删除、2-不能删除
		Wrapper wrapper = Condition.create().like("product_name", string);

		if (CommonUtil.isBlank(state)) {
			state = 0;
		}
		wrapper.eq("mp.state", state);
		// if (!CommonUtil.isBlank(productName)) {
		// wrapper.like("mp.product_name", string);
		// }
		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("add_time", false);
		}
		Page resultPage = iMerchantProductService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "merchant/merchantProduct/list";
	}

	/**
	 * 去新增
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/toInsert")
	@RequiresPermissions("/merchant/merchantProduct/toInsert")
	public String toInsert(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper = Condition.create().ne("del", 1);
		map.put("typeAll", iMerchantProductTypeService.selectList(wrapper));
		return "merchant/merchantProduct/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/merchant/merchantProduct/toInsert")
	@ResponseBody
	public Object insert(@Valid MerchantProduct merchant_product, @Valid MerchantProductNorm merchantProductNorm, String[] picUrls, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 添加时间
		merchant_product.setAddTime(CommonUtil.getDate());
		// 获取当前操作人，当操作人为null时，表示自动录入
		merchant_product.setOperator(getUserId());
		// 是否删除：0-未删除、1-已删除、2-不能删除
		merchant_product.setDel(0);
		// 状态 0正常 1下架 2库存不足
		merchant_product.setState(0);
		if (iMerchantProductService.insertMerchantProduct(merchant_product, merchantProductNorm, picUrls)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	/**
	 * 去修改
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdate")
	@RequiresPermissions("/merchant/merchantProduct/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Wrapper ptwrapper = Condition.create().ne("del", 1);
		map.put("typeAll", iMerchantProductTypeService.selectList(ptwrapper));
		MerchantProduct merchantProduct = iMerchantProductService.selectById(id);
		map.put("record", merchantProduct);
		String parameterStrs = merchantProduct.getCustomProperties();
		List<Map> parameter = JSON.parseObject(parameterStrs, List.class);
		map.put("parameter", parameter);
		Wrapper picswrapper = Condition.create().eq("merchant_product_id", merchantProduct.getMerchantProductId());
		map.put("pics", iMerchantProductPicsService.selectList(picswrapper));
		Wrapper pnwrapper = Condition.create().eq("merchant_product_id", merchantProduct.getMerchantProductId());
		map.put("pn", iMerchantProductNormService.selectOne(pnwrapper));
		return "merchant/merchantProduct/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/merchant/merchantProduct/toUpdate")
	@ResponseBody
	public Object update(@Valid MerchantProduct merchant_product, @Valid MerchantProductNorm merchantProductNorm, String[] picUrls, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// region 验证商品重名
		Wrapper pnameswrapper = Condition.create().eq("product_name", merchant_product.getProductName()).ne("merchant_product_id", merchant_product.getMerchantProductId());
		MerchantProduct merchantProduct = iMerchantProductService.selectOne(pnameswrapper);
		if (!CommonUtil.isBlank(merchantProduct)) {
			return ajaxError("名称已经存在");
		}
		// endregion
		if (iMerchantProductService.updateMerchantProduct(merchant_product, merchantProductNorm, picUrls)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去删除
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("/merchant/merchantProduct/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		if (iMerchantProductService.deleteBatchIds(Arrays.asList(id))) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去下架
	 * 
	 * @param id
	 * @param merchantProduct
	 * @param merchantProductId
	 * @param state
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateProductState")
	@RequiresPermissions("/merchant/merchantProduct/updateProductState")
	@ResponseBody
	public Object updateProductState(String id, MerchantProduct merchantProduct, String merchantProductId, Integer state, HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (iMerchantProductService.updateProductState(id, merchantProduct)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 获取商家资源
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/getMerchantAsset")
	@RequiresPermissions("/merchant/merchantProduct/toInsert")
	public String getMerchantAsset(String returnPage, String commonTypeId, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		dwzPageBean.getCountResultMap().put("commonTypeId", commonTypeId);

		Wrapper mptwrapper = Condition.create().ne("del", 1).eq("type_class", 1);
		map.put("typeAll", iMerchantCommonTypeService.selectList(mptwrapper));
		// 查找所有分组信息
		// 类型 0容量单位 (如ml ,l等) 1资源分组名称
		map.put("merchantCommonTypes", iMerchantCommonTypeService.selectList(Condition.create().eq("type_class", "1").ne("del", 1)));
		Wrapper wrapper = Condition.create().ne("ast.del", 1).and("ast.common_type_id = ct.common_type_id");
		if (!CommonUtil.isBlank(commonTypeId)) {
			wrapper.eq("ast.common_type_id", commonTypeId);
		}
		System.out.println(wrapper.getSqlSegment());
		Page resultPage = iMerchantAssetService.selectVoPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		if (CommonUtil.isEquals(returnPage, "cover")) {
			return "merchant/merchantProduct/cover";
		}
		return "merchant/merchantProduct/pictures";
	}

	/**
	 * 查询商品名称
	 * 
	 * @param id
	 * @param shop
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getProductName")
	@ResponseBody
	public Object getProductName(String productName, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper = Condition.create().like("product_name", productName).ne("del", 1);
		wrapper.setSqlSelect("product_name");
		List list = iMerchantProductService.selectList(wrapper);
		return JSON.toJSONString(list);
	}

	/**
	 * 导出商品设置Excel
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/merchantProductexport")
	@RequiresPermissions("/merchant/merchantProduct/merchantProductexport")
	public String merchantProductexport(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().eq("state", 0);
		// 根据用户id获取角色
		boolean isDirector = true;
		List<Role> roles = getRoleList();
		for (Role role : roles) {
			if ("运营主管".equals(role.getName())) {
				isDirector = false;
			}
		}
		if (isDirector) {
			wrapper.eq("maid", getUserId());
		}
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iMerchantProductService.selectVoByPage(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "商品设置", ExcelType.XSSF);
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, MerchantProductVo.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "商品设置");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称
	}

}
